package com.and9.mchen.mweather.cw.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


final public class PropertyUtil {

	private final static Log log = LogFactory.getLog(PropertyUtil.class);
	private static Hashtable<String, Properties> pptContainer = new Hashtable<String, Properties>();
	private PropertyUtil(){}
 
	public final static String getValue(String propertyFilePath, String key) {
		Properties ppts = getProperties(propertyFilePath);
		return ppts == null ? null : ppts.getProperty(key);
	}

	public final static synchronized Properties getProperties(String propertyFilePath) {
		if (propertyFilePath == null) {
			log.error("propertyFilePath is null!");
			return null;
		}
	 
		Properties ppts = pptContainer.get(propertyFilePath);
		if (ppts == null) {
			ppts = loadPropertyFile(propertyFilePath);
			if (ppts != null) {
				pptContainer.put(propertyFilePath, ppts);
			}
		}
		return ppts;
	}

	private static Properties loadPropertyFile(String propertyFilePath) {
		InputStream is = PropertyUtil.class.getResourceAsStream(propertyFilePath);
		if (is == null) {
			return loadPropertyFileByFileSystem(propertyFilePath);
		}
		Properties ppts = new Properties();
		try{
			ppts.load(is);
			return ppts;
		}catch(Exception e){
			log.debug("加载属性文件出错:" + propertyFilePath, e);
			return null;
		}
	}

 
	private static Properties loadPropertyFileByFileSystem(final String propertyFilePath) {
		try{
			Properties ppts = new Properties();
			ppts.load(new FileInputStream(propertyFilePath));
			return ppts;
	 	}catch(FileNotFoundException e){
	 		log.error("FileInputStream(\"" + propertyFilePath+ "\")! FileNotFoundException: " + e);
	 		return null;
	 	}catch(IOException e){
	 		log.error("Properties.load(InputStream)! IOException: " + e);
	 		return null;
	 	}
	}

 
	public final static Properties removePropertyFile(String propertyFilePath) {
		return pptContainer.remove(propertyFilePath);
	}

 
	public final static Properties reloadPropertyFile(String propertyFilePath) {
		removePropertyFile(propertyFilePath);
		return getProperties(propertyFilePath);
	}

}
